package com.ruoyi.book.service.impl;

import java.util.List;

import com.ruoyi.book.domain.Booklabel;
import com.ruoyi.book.domain.Label;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.book.mapper.BookMapper;
import com.ruoyi.book.domain.Book;
import com.ruoyi.book.service.IBookService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 书籍Service业务层处理
 *
 * @author ruoyi
 * @date 2023-05-06
 */
@Service
public class BookServiceImpl implements IBookService {
    @Autowired
    private BookMapper bookMapper;

    /**
     * 查询书籍
     *
     * @param id 书籍主键
     * @return 书籍
     */
    @Override
    public Book selectBookById(Long id) {
        return bookMapper.selectBookById(id);
    }

    /**
     * 查询书籍列表
     *
     * @param book 书籍
     * @return 书籍
     */
    @Override
    public List<Book> selectBookList(Book book) {
        return bookMapper.selectBookList(book);
    }

    /**
     * 新增书籍
     *
     * @param book 书籍
     * @return 结果
     */
    @Override
    @Transactional
    public int insertBook(Book book) {
        //System.out.println(book.getLabelsList()+">??>>#####");
        int r = bookMapper.insertBook(book);

        for (Label b : book.getLabelsList()) {
            Booklabel bb=new Booklabel();
            bb.setBookid(book.getId());
            bb.setLabid(b.getId());
            this.bookMapper.insertBookLabel(bb);
        }

        return r;
    }

    /**
     * 修改书籍
     *
     * @param book 书籍
     * @return 结果
     */
    @Override
    public int updateBook(Book book) {
        //先删除，重新插入
        this.bookMapper.delBookLabel(book.getId());
        for (Label b : book.getLabelsList()) {
            Booklabel bb=new Booklabel();
            bb.setBookid(book.getId());
            bb.setLabid(b.getId());
            this.bookMapper.insertBookLabel(bb);
        }
        return bookMapper.updateBook(book);
    }

    /**
     * 批量删除书籍
     *
     * @param ids 需要删除的书籍主键
     * @return 结果
     */
    @Override
    public int deleteBookByIds(Long[] ids) {
        for(Long bid:ids){
            this.bookMapper.delBookLabel(bid);
        }
        return bookMapper.deleteBookByIds(ids);
    }

    /**
     * 删除书籍信息
     *
     * @param id 书籍主键
     * @return 结果
     */
    @Override
    public int deleteBookById(Long id) {
        this.bookMapper.delBookLabel(id);
        return bookMapper.deleteBookById(id);
    }
}
